<?php
/*
	搜索类
*/
class Keywords{
	
	public $keywords;
	public $counts;
	public $max_page;
	private $sps;
	/*
		初始化搜索
	*/
	public function __construct($keywords,$cat_id=0){
		//可能出现的连词
		$this->lian_ci  = array('but','on','the','and','of','off','to','by','*','/');
		
		//搜索条件
		$this->keywords = $GLOBALS['Main']->escapeString(strtolower(trim($keywords)));
		$this->keywords = preg_replace("/[-+]|( and )|( but )|( on )|( the )|( of )|( off )|( to )|( by )|( \* )/"," ",$this->keywords);
		
		$where = $this->getWhere($this->keywords);
		
		
		//附加条件
		$search = @$_SESSION['search'];
		if($cat_id)
		{
			$where .= " and g.cat_id='".$cat_id."'";
		}
		$price = $GLOBALS['Goods']->priceLimit('g.');
		if($price)
		{
			$where .="  $price";	
		}
		
		$this->where = $where.' and g.is_delete=0 ';
		
		
	}

	private function getWhere($kw){
	
	
   
		$arr = preg_split("/[+ _-]/i",$kw);
     
		$where = array();
       
        foreach ($arr AS $key => $val)
        {
            if($val)
			{
				$val        = $GLOBALS['Main']->escapeString(trim($val));
				$sc_dsad    =  " OR g.keywords regexp '$val'  ";
				$str1		=	"( g.goods_name regexp '$val'  $sc_dsad)";//"( instr(g.goods_name,' $val ') $sc_dsad)";
				$where[]    = $str1;
				$this->sps[] = strtolower($val);
			}
       }
      
	    $join1 = join($where," and ");
		$join2 = join($where," or ");
		$res = $join1;
		//echo $res;
		//die();
		
		return $join1;
	}
	
	/*
		取得总条数和总页数
	*/
	public function setCount(){
		
		
		$size = $GLOBALS['size'];
		$sql = "select count(g.goods_id) as count from goods as g where ".$this->where." ";
		
		$res = $GLOBALS['db']->getone($sql);
		if(!$res)
		{
			$kwd = preg_replace("/-/"," ",$this->keywords);
			//$url = 'https://www.google.com/search?q='.$this->keywords.'&domains=ethnicharms.com&sitesearch=ethnicharms.com';
			//header("location:$url");
			//exit();
		}
		$this->counts	= $res;
		$this->max_page = ceil($res/$size);
		return $res;
		
	}

	/*
		搜索列表
	*/
	public function getSearchList($start,$size,$sort='goods_id',$order='desc'){
		
		
		$limit = 'limit '.$start.','.$size.'';
		$order = 'order by '.$sort.' '.$order.'';
		
		#$sql   = "select g.goods_name,g.shop_price,g.market_price,g.original_img,g.goods_thumb,g.goods_id,g.cat_id from goods as g where ".$this->where." ".$order." ".$limit.";";
		$sql   = "select g.goods_id from goods as g where ".$this->where." ".$order." ".$limit.";";
		
		
		$ids = $GLOBALS['db']->getAll($sql);
		
		foreach($ids as $k=>$v)
		{
			
			$goods_ids[] = $v['goods_id'];
		}
		
		
		$goods_list = array();

		$id_where = 'g.goods_id='.join($goods_ids," or g.goods_id=");
		
		$sql = "select g.goods_name,g.shop_price,g.market_price,g.original_img,g.goods_thumb,g.goods_id,g.cat_id,g.keywords from goods as g  where  $id_where order by cat_id desc";
		
		$goods_list = $GLOBALS['db']->getAll($sql);
		foreach($goods_list as $key=>$val)
		{
			$val = $GLOBALS['Goods']->goodsFormat($val);
			
			foreach($this->sps as $s_v)
			{
			
				$val['goods_name'] = preg_replace("/".$s_v."/i","<em class='green'>$s_v</em>",$val['goods_name']);
				$val['keywords'] = preg_replace("/".$s_v."/i","<em class='green'>$s_v</em>",$val['keywords']);
			}
			$goods_list[$key] = $val;
		}
		
		
		return $goods_list;
	}

	/*
		取得相关的关键词
	*/
	public function relatedSearch(){
		
		return array();
		if(isset($_SESSION['search']['relate_words'][$this->keywords]))
		{
			return $_SESSION['search']['relate_words'][$this->keywords];
		}
		
		$relate_words = array();
		$limit = 10;
		
		$sql = "select g.goods_name from goods  as g where ".$this->where." ";
		$query = mysql_query($sql);
		if(!$query)
			return false;
		
		$res =	array();
		$i=0;
		while($row = mysql_fetch_row($query,MYSQL_ASSOC))
		{
			if(strlen($this->keywords)<3)
			{
				$relate = $this->getRelateWords($row['goods_name'],'words');
			}
			else
			{
				if($i%2==0)
				{
					$relate = $this->getRelateWords($row['goods_name'],'fore');
				}
				else
				{
					$relate = $this->getRelateWords($row['goods_name'],'back');
				}
			}
			if($relate)
			{
				$relate_words[]=$relate;
			}
			$relate_words = array_unique($relate_words);
			
			if(count($relate_words)>10)
			{
				break;
			}
			$i++;
			
		}
		
		natsort($relate_words);
		if(!isset($_SESSION['search']['relate_words'][$this->keywords]))
		{
			$_SESSION['search']['relate_words'][$this->keywords] = $relate_words;
		}
		return $relate_words;
		
		
	}
	/*
		取关键词前后的单词
		如果前面为空，则取后面
		如果后面为空，则取前面
	*/
	private function getRelateWords($words,$type){
		
		$relate_words = $this->getWords($words,$type);
		
		if(strtolower(trim($relate_words))==$this->keywords)
		{
			$relate_words = '';
		}
		$compile = array("/[\.;,_\d+-]/","/[\(\)]/");
		$re      = array('','');
		$relate_words = preg_replace($compile,$re,$relate_words);
		
		return strtolower($relate_words);
			
	}
	/*
		取得一个完整的单词
	*/
	private function getWords($words,$type)
	{
		
		$relate_words = '';
		
		$sp      = preg_split("/ /",$words);
		if(count($sp)>0)
		{
			foreach($sp as $key=>$val)
			{
				
				if(!in_array(strtolower(@$sp[$key+1]),$this->lian_ci))
				{
					if($type=='words' && (strpos(strtolower($val),$this->keywords)===0))
					{
						
						$relate_words = $val;
						
					}
					elseif(strpos(strtolower($val),$this->keywords)===0 || strpos(strtolower($val),$this->keywords)>0)
					{
						
						if(!in_array(strtolower(@$sp[$key-1]),$this->lian_ci) && $type='fore')
						{
							$relate_words = @$sp[$key-1].' '.$val;
						}
						if(!in_array(strtolower(@$sp[$key+1]),$this->lian_ci) && $type='back')
						{
							$relate_words = $val.' '.@$sp[$key+1];
						}
							
						
					}
				}
			}
		}
		
		return $relate_words;
	
	}

	/*
		取得搜索词所在的分类
	*/

	public function relateCategories(){
		
		if(isset($_SESSION['search']['category'][$this->keywords]))
		{
			//return $_SESSION['search']['category'][$this->keywords];
		}
		$sql = "select g.cat_id from goods as g inner join category as c on g.cat_id=c.cat_id where ".$this->where." and c.is_show=1";
		
		$res = $GLOBALS['db']->getAll($sql);
		
		$cat_ids = array();
		//取得分类出现次数并排序
		foreach($res as $key=>$val)
		{
			$cat_ids[] = $val['cat_id'];
			
		}
		$count_times = array_count_values($cat_ids);
		arsort($count_times);
		
		$times = array();
		//获取分类名称
		$t = array_values($count_times);
		foreach(array_keys($count_times) as $key=>$cat_id)
		{
			$cat =  $this->getCatName($cat_id).' ( '.$t[$key].' )';
			$url = '<a href="'.SEARCH.'-0-'.$cat_id.'-' . $this->keywords . '.html">' . $cat . '</a> ';
			$times[$cat_id]    = $url;
			
			
			
		}
		//print_r($times);
		if(!isset($_SESSION['search']['category'][$this->keywords]))
		{
			$_SESSION['search']['category'][$this->keywords] = $times;
		}
		
		return $times;
		
	}
	/*
		获取父分类
	*/
	public function getParent($cat_id){
		$sql = "select cat_id,cat_name from category where cat_id='".$cat_id."';";
		$query = mysql_query($sql);
		$row = mysql_fetch_row($query,MYSQL_ASSOC);
		return $row;
	}
	/*
		获取分类名称
	*/
	public function getCatName($cat_id){
		$sql = "select cat_name from category where cat_id='".$cat_id."';";

		$res = $GLOBALS['db']->getone($sql);
		return $res;
		
	
	}
	/*
		取得相关属性
	*/

	public function relateAttr(){
		if(isset($_SESSION['search']['relate_attr'][$this->keywords]))
		{
			return $_SESSION['search']['relate_attr'][$this->keywords];
		}
		$color = array('Black','White','Silver','Ivory','Red','Pink','Gold','Blue','Brown','Purple','Yellow','Green','Gray');
		$metal = array('silver','gold','Platinum','Titanium','Alloy','Crystal','Pearl','Aluminum','Glass','Stainless Steel','Wood','Metal','Fabric','Paper','Cubic Zirconia','Leather','Cotton','Gem','Linen','Canvas','Polyester','Fabric','Nylon','Satin','Shell','Plastic');
		$style = array('Shoulder','Tote','Hobo');

		$sql   = "select t.goods_id ,t.tag_words from tag as t inner join goods as g on g.goods_id=t.goods_id where ".$this->where."";
		
		$query = mysql_query($sql);
		while($row = mysql_fetch_row($query,MYSQL_ASSOC))
		{
			$res[$row['tag_words']][] = $row['goods_id'];
		}
		$keys = @array_keys($res) ? @array_keys($res) : array();
		$attr = array();
		
		foreach($keys as $k=>$v)
		{
			$attr[][$v] = count($res[$v]);
		}
		
		//颜色,材料,风格
		$relate_color = array();
		$relate_metal = array();
		$relate_style = array();
		foreach($attr as $val)
		{
			$k = array_keys($val);
			$v = array_values($val);
			$vs = $v[0];
			$ks = $k[0];
			if(in_array($ks,$color))
			{
				$relate_color[$ks] = $vs;
			}
			if(in_array($ks,$metal))
			{
				$relate_metal[$ks] = $vs;
			}
			if(in_array($ks,$style))
			{
				$relate_style[$ks] = $vs;
			}
		}
		
		arsort($relate_color);
		arsort($relate_metal);
		arsort($relate_style);
		$res = array('relate_color'=>$relate_color,'relate_metal'=>$relate_metal,'relate_style'=>$relate_style);
		if(!isset($_SESSION['search']['relate_attr'][$this->keywords]))
		{
			$_SESSION['search']['relate_attr'][$this->keywords] = $res;
		}
		return $res;
		
	}
	

}
?>